// 获取DOM元素
const qrcodeInput = document.getElementById('qrcodeInput');
const errorMessageEl = document.getElementById('errorMessage');
const downloadButton = document.getElementById('downloadButton');
let qrcode = null;

// 显示错误消息
function showError(message) {
    errorMessageEl.textContent = message;
    errorMessageEl.classList.add('visible');
}

// 隐藏错误消息
function hideError() {
    errorMessageEl.textContent = '';
    errorMessageEl.classList.remove('visible');
}

// 获取合适的QR码配置
function getQRConfig(text) {
    const byteLength = encodeURIComponent(text).replace(/%[0-9A-F]{2}/g, '_').length;
    
    if (byteLength <= 100) {
        return {
            correctLevel: QRCode.CorrectLevel.H  // 30% 纠错
        };
    } else if (byteLength <= 250) {
        return {
            correctLevel: QRCode.CorrectLevel.Q  // 25% 纠错
        };
    } else {
        return {
            correctLevel: QRCode.CorrectLevel.L  // 7% 纠错
        };
    }
}

// 检查文本长度并返回合适的QR码版本和建议
function checkTextLength(text) {
    if (!text || text.trim() === '') {
        return {
            valid: false,
            message: '请输入要生成二维码的文本'
        };
    }

    const byteLength = encodeURIComponent(text).replace(/%[0-9A-F]{2}/g, '_').length;
    const MAX_LENGTH = 300;

    if (byteLength <= MAX_LENGTH) {
        return {
            valid: true,
            message: byteLength > 250 ? '注意：文本较长，已降低纠错级别以确保生成成功' : ''
        };
    } else {
        return {
            valid: false,
            message: `文本太长（${byteLength} 字节，建议单个二维码不超过 ${MAX_LENGTH} 字节）。已自动分段处理。`
        };
    }
}

// 生成二维码
function generateQRCode(text) {
    if (!text || text.trim() === '') {
        showError('请输入要生成二维码的文本');
        return;
    }

    const lengthCheck = checkTextLength(text);
    if (!lengthCheck.valid) {
        showError(lengthCheck.message);
        return;
    }

    if (lengthCheck.message) {
        showError(lengthCheck.message);
    } else {
        hideError();
    }
    
    try {
        const qrcodeContainer = document.getElementById('qrcode');
        if (!qrcodeContainer) {
            console.error('QR code container not found');
            return;
        }

        qrcodeContainer.innerHTML = '';
        
        const config = getQRConfig(text.trim());
        
        qrcode = new QRCode(qrcodeContainer, {
            text: text.trim(),
            width: 256,
            height: 256,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: config.correctLevel
        });
    } catch (error) {
        console.error('QR Code generation error:', error);
        showError('生成二维码时出错：' + error.message);
    }
}

// 分段生成多个二维码
function generateMultipleQRCodes(text) {
    if (!text || text.trim() === '') {
        showError('请输入要生成二维码的文本');
        return;
    }

    const MAX_LENGTH = 250;
    const chunks = [];
    const trimmedText = text.trim();
    
    for (let i = 0; i < trimmedText.length; i += MAX_LENGTH) {
        chunks.push(trimmedText.slice(i, i + MAX_LENGTH));
    }

    try {
        const container = document.getElementById('qrcode');
        if (!container) {
            console.error('QR code container not found');
            return;
        }

        container.innerHTML = '';

        chunks.forEach((chunk, index) => {
            const wrapper = document.createElement('div');
            wrapper.className = 'qrcode-wrapper';
            
            const label = document.createElement('div');
            label.className = 'qrcode-label';
            label.textContent = `第 ${index + 1}/${chunks.length} 部分`;
            
            const qrcodeDiv = document.createElement('div');
            wrapper.appendChild(label);
            wrapper.appendChild(qrcodeDiv);
            container.appendChild(wrapper);

            const config = getQRConfig(chunk);

            new QRCode(qrcodeDiv, {
                text: chunk,
                width: 256,
                height: 256,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: config.correctLevel
            });
        });

        showError(chunks.length > 1 
            ? `文本已被分成 ${chunks.length} 个二维码` 
            : '');

    } catch (error) {
        console.error('QR Code generation error:', error);
        showError('生成二维码时出错：' + error.message);
    }
}

// 下载二维码
function downloadQRCode() {
    const canvas = document.querySelectorAll('#qrcode canvas');
    if (!canvas || canvas.length === 0) {
        showError('没有可下载的二维码');
        return;
    }

    try {
        if (canvas.length === 1) {
            const url = canvas[0].toDataURL('image/png');
            const a = document.createElement('a');
            a.href = url;
            a.download = 'qrcode.png';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        } else {
            canvas.forEach((c, index) => {
                const url = c.toDataURL('image/png');
                const a = document.createElement('a');
                a.href = url;
                a.download = `qrcode-part${index + 1}.png`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        }
    } catch (error) {
        console.error('QR Code download error:', error);
        showError('下载二维码时出错：' + error.message);
    }
}

// 监听输入变化
qrcodeInput.addEventListener('input', (e) => {
    const text = e.target.value;
    if (!text || text.trim() === '') {
        const container = document.getElementById('qrcode');
        if (container) {
            container.innerHTML = '';
        }
        hideError();
        return;
    }

    const lengthCheck = checkTextLength(text);
    if (lengthCheck.valid) {
        generateQRCode(text);
    } else {
        generateMultipleQRCodes(text);
    }
});

// 监听下载按钮点击
downloadButton.addEventListener('click', downloadQRCode); 